package com.fs.m.server.util;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: zhuguoyin
 * Date: 13-10-7
 * Time: 下午3:19
 * To change this template use File | Settings | File Templates.
 */
public class GsonUtil {

    private static Gson gson;

    static {
        gson = new GsonBuilder().registerTypeAdapter(Date.class, new UtilDateSerializer()).create();
    }

    private static class UtilDateSerializer implements JsonSerializer<Date>,JsonDeserializer<Date> {
        @Override
        public JsonElement serialize(Date date, Type type,
                                     JsonSerializationContext context) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return new JsonPrimitive(df.format(date));
        }

        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            DateFormat df;
            String dateString = json.getAsJsonPrimitive().getAsString();
            if (dateString.length() <= 10) {
                df = new SimpleDateFormat("yyyy-MM-dd");
            } else {
                df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            }
            try {
                return df.parse(dateString);
            } catch (ParseException e) {
                throw new JsonParseException(e);
            }
        }
    }


    public static String toJSon(Object o) {
        return gson.toJson(o);
    }

    public static <T> T fromJson(String s, Class<T> type) {
        return gson.fromJson(s, type);
    }
}
